#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <string>
#include "httplib/httplib.h"
#include "searcher.hpp"
#include "log.hpp"

const std::string root_path = "./wwwroot";
const std::string input = "./data/raw_htmls/raw.bin";
// 注：自动更新工作转用crontab工具进行
//const unsigned int update_interval = 432000; //每5天间隔检查一次更新
ns_searcher::Searcher searcher; //放在全局，便于重新建立索引

class NetWork
{
public:
    NetWork()
    {
        signal(SIGPIPE, SIG_IGN);
    }
};

static NetWork nt;
// 注：自动更新工作转用crontab工具进行
/*
void HtmlUpdate(int signo)
{
    std::cout << "get signo:" << signo << std::endl;
    pid_t id = fork();
    //子进程获取最新boost
    if(id == 0) { execlp("python3", "python3", "./htmlUpdate_d/boostget.py", nullptr); }
    else if (id > 0)
    {
        int status = 0;
        int r = waitpid(id, &status, 0);
        if(r < 0) { ns_log::lg(ns_log::ERROR, "waitpid HtmlUpdate err"); }
        if(status == 1) //当boostget.py进行了boost库下载更新时才重新处理boost库
        {
            id = fork();
            //子进程解压并处理获取的最新boost
            if(id == 0) { execlp("bash", "bash", "./htmlUpdate_d/htmldispos.bash", nullptr); }
            else if (id > 0) {
                // signal(SIGCHLD, SIG_IGN);
                r = waitpid(id, nullptr, 0); //等待子进程处理完成
                if(r < 0) { ns_log::lg(ns_log::ERROR, "waitpid htmldispos err"); }
                searcher.InitSearcher(input); //重新建立索引
                alarm(update_interval);
                ns_log::lg(ns_log::LOG, "版本更新成功...");
                std::cout << "版本更新成功..." << std::endl;
            }
            else { ns_log::lg(ns_log::ERROR, "fork htmldispos err"); }
        }
        else {
            std::cout << "无需更新..." << std::endl;
            ns_log::lg(ns_log::LOG, "无需更新...");
        }
    }
    else { ns_log::lg(ns_log::ERROR, "fork HtmlUpdate err"); }
}
// 注：自动更新工作转用crontab工具进行
void autoupdate()
{
    signal(SIGALRM, HtmlUpdate);
    alarm(update_interval); //定时发送信号
}
*/
int main()
{
    searcher.InitSearcher(input);
    // autoupdate(); //启动自动检测更新
    // 注：自动更新工作转用crontab工具进行
    httplib::Server svr;
    svr.set_base_dir(root_path);
    svr.Get("/s", [&](const httplib::Request& req, httplib::Response& rsp) \
    {
        if(!req.has_param("word")) {
            rsp.set_content("no key word!", "text/plain; charset=utf-8");
            return;
        }
        std::string word = req.get_param_value("word");
        ns_log::lg(ns_log::LOG, "searching: %s", word.c_str());
        // std::cout << "searching: " << word << std::endl;
        std::string json_string;
        searcher.Search(word, &json_string);
        rsp.set_content(json_string, "application/json");
    });
    std::cout << "服务启动..." << std::endl;
    daemon(1, 0); //守护进程
    svr.listen("0.0.0.0", 8080);
    ns_log::lg(ns_log::LOG, "服务启动...");
    return 0;
}
